package com.xbts.system.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.*;
import com.xbts.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbts.system.mapper.CnVirtuallyUserBuyLogMapper;
import com.xbts.common.utils.DateUtils;
import com.xbts.common.utils.SecurityUtils;

/**
 * 用户购买记录（虚拟）Service业务层处理
 * 
 * @author xbts
 * @date 2023-11-30
 */
@Service
public class CnVirtuallyUserBuyLogServiceImpl  extends ServiceImpl<CnVirtuallyUserBuyLogMapper, CnVirtuallyUserBuyLog> implements ICnVirtuallyUserBuyLogService {

    @Autowired
    private CnVirtuallyUserBuyLogMapper cnVirtuallyUserBuyLogMapper;

    @Autowired
    private ICnVirtuallyUserHwAccountService virtuallyUserHwAccountService;

    @Autowired
    private ICnGovernmentCloudService governmentCloudService;
    @Autowired
    private ICnGovernmentCloudTypeService governmentCloudTypeService;
    @Autowired
    private ICnCloudMarketTypeService cnCloudMarketTypeService;
    @Autowired
    private ICnCloudMarketService cnCloudMarketService;
    @Autowired
    private ICnCommonCloudTypeService cnCommonCloudTypeService;
    @Autowired
    private ICnCommonCloudService cnCommonCloudService;
    @Autowired
    private ICnCloudMarketSkuService cnCloudMarketSkuService;


    /**
     * 查询用户购买记录（虚拟）列表
     *
     * @param cnVirtuallyUserBuyLog 用户购买记录（虚拟）
     * @return 用户购买记录（虚拟）
     */
    @Override
    public List<CnVirtuallyUserBuyLog> selectCnVirtuallyUserBuyLogList(CnVirtuallyUserBuyLog cnVirtuallyUserBuyLog) {
        QueryWrapper<CnVirtuallyUserBuyLog> queryWrapper = cnVirtuallyUserBuyLog.queryWrapper();
        return cnVirtuallyUserBuyLogMapper.selectCnVirtuallyUserBuyLogList(queryWrapper);
    }

    /**
     * 查询用户购买记录（虚拟）
     *
     * @param userId 用户购买记录（虚拟）主键
     * @return 用户购买记录（虚拟）
     */
    @Override
    public CnVirtuallyUserBuyLog selectCnVirtuallyUserBuyLogByUserId(String userId) {
        return getById(userId);
    }

    /**
     * 新增用户购买记录（虚拟）
     *
     * @param cnVirtuallyUserBuyLog 用户购买记录（虚拟）
     * @return 结果
     */
    @Override
    public boolean insertCnVirtuallyUserBuyLog(CnVirtuallyUserBuyLog cnVirtuallyUserBuyLog) {
        List<CnVirtuallyUserBuyLog> list = cnVirtuallyUserBuyLog.getList();

        for (CnVirtuallyUserBuyLog buyLog : list) {
            buyLog.setProductTypeName(cnVirtuallyUserBuyLog.getProductTypeName());
            buyLog.setServiceTypeName(cnVirtuallyUserBuyLog.getServiceTypeName());
            buyLog.setUserId(cnVirtuallyUserBuyLog.getUserId());
            buyLog.setCreateBy(SecurityUtils.getUserId().toString());
            buyLog.setCreateTime(new Date());
        }

        return saveBatch(list);
    }

    /**
     * 修改用户购买记录（虚拟）
     *
     * @param cnVirtuallyUserBuyLog 用户购买记录（虚拟）
     * @return 结果
     */
    @Override
    public boolean updateCnVirtuallyUserBuyLog(CnVirtuallyUserBuyLog cnVirtuallyUserBuyLog) {
        cnVirtuallyUserBuyLog.setUpdateBy(SecurityUtils.getUserId().toString());
        cnVirtuallyUserBuyLog.setUpdateTime(DateUtils.getNowDate());
        return updateById(cnVirtuallyUserBuyLog);
    }

    /**
     * 批量删除用户购买记录（虚拟）
     *
     * @param ids 需要删除的用户购买记录（虚拟）主键
     * @return 结果
     */
    @Override
    public boolean deleteCnVirtuallyUserBuyLogByIds(List<String> ids) {
        return removeBatchByIds(ids);
    }

    /**
     * 删除用户购买记录（虚拟）信息
     *
     * @param userId 用户购买记录（虚拟）主键
     * @return 结果
     */
    @Transactional
    @Override
    public boolean deleteCnVirtuallyUserBuyLogById(String userId) {
      return removeById(userId);
    }

    @Override
    public Object productTypeNameList() {

        List<Map<String, Object>> result = new ArrayList<>();
        // 政务云
        Map<String, Object> govMap = new HashMap<>();
        govMap.put("name", "政务云");
        govMap.put("type", "1");
        List<CnGovernmentCloudType> govList = governmentCloudTypeService.list(new LambdaQueryWrapper<CnGovernmentCloudType>()
                .eq(CnGovernmentCloudType::getDeleteFlag, 0));
        List<Map<String, Object>> govTypeMapList = new ArrayList<>();
        for (CnGovernmentCloudType type : govList) {
            Map<String, Object> govTypeMap = new HashMap<>();
            govTypeMap.put("name", type.getServerType());
            govTypeMap.put("id", type.getServerTypeId());
            govTypeMapList.add(govTypeMap);
        }
        govMap.put("children", govTypeMapList);
        result.add(govMap);
        // 云市场
        Map<String, Object> marketMap = new HashMap<>();
        marketMap.put("name", "云市场");
        marketMap.put("type", "2");
        List<CnCloudMarketType> marketList = cnCloudMarketTypeService.list();
        List<Map<String, Object>> marketTypeMapList = new ArrayList<>();
        for (CnCloudMarketType type : marketList) {
            Map<String, Object> marketTypeMap = new HashMap<>();
            marketTypeMap.put("name", type.getName());
            marketTypeMap.put("id", type.getId());
            marketTypeMapList.add(marketTypeMap);
        }
        marketMap.put("children", marketTypeMapList);
        result.add(marketMap);
        // 公有云
        Map<String, Object> commonMap = new HashMap<>();
        commonMap.put("name", "公有云");
        commonMap.put("type", "3");
        List<CnCommonCloudType> commonList = cnCommonCloudTypeService.list(new LambdaQueryWrapper<CnCommonCloudType>()
                .eq(CnCommonCloudType::getDeleteFlag, 0));
        List<Map<String, Object>> commonTypeMapList = new ArrayList<>();
        for (CnCommonCloudType type : commonList) {
            Map<String, Object> commonTypeMap = new HashMap<>();
            commonTypeMap.put("name", type.getServerType());
            commonTypeMap.put("id", type.getServerTypeId());
            commonTypeMapList.add(commonTypeMap);
        }
        commonMap.put("children", commonTypeMapList);
        result.add(commonMap);
        // 云服务器
        Map<String, Object> cloudMap = new HashMap<>();
        cloudMap.put("name", "云服务器");
        cloudMap.put("type", "4");
        List<Map<String, Object>> cloudMapList = new ArrayList<>();
        Map<String, Object> cloudTypeMap = new HashMap<>();
        cloudTypeMap.put("name", "云服务器");
        cloudTypeMap.put("id", 1);
        cloudTypeMap.put("children", cloudMapList);
        cloudMapList.add(cloudTypeMap);
        result.add(cloudMap);
        return result;
    }

    @Override
    public Object productNameList(String type, String id) {
        List<Map<String, Object>> result = new ArrayList<>();

        if ("1".equals(type)) {
            List<CnGovernmentCloud> list = governmentCloudService.list(new LambdaQueryWrapper<CnGovernmentCloud>()
                    .eq(CnGovernmentCloud::getDeleteFlag, 0)
                    .eq(CnGovernmentCloud::getServerTypeId, id));
            for (CnGovernmentCloud governmentCloud : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("productName", governmentCloud.getServerName());
                map.put("productConfig", "CPU:" + (StringUtils.isBlank(governmentCloud.getCpu()) ? "无" : governmentCloud.getCpu())
                        + " 内存:" + (StringUtils.isBlank(governmentCloud.getMemory()) ? "无" : governmentCloud.getMemory())
                        + " 硬盘大小:" + (StringUtils.isBlank(governmentCloud.getHardDisk()) ? "无" : governmentCloud.getHardDisk())
                        + " 防御:" + (StringUtils.isBlank(governmentCloud.getDefense()) ? "无" : governmentCloud.getDefense())
                        + " 带宽:" + (StringUtils.isBlank(governmentCloud.getBandwidth()) ? "无" : governmentCloud.getBandwidth())
                        + " 其他:" + (StringUtils.isBlank(governmentCloud.getOther()) ? "无" : governmentCloud.getOther()));
                map.put("amount", governmentCloud.getPrice());
                map.put("productCount", 1);
                result.add(map);
            }
        } else if ("2".equals(type)) {
            List<CnCloudMarket> list = cnCloudMarketService.list(new LambdaQueryWrapper<CnCloudMarket>()
                    .eq(CnCloudMarket::getDeleteFlag, 0)
                    .and(v -> {
                        v.eq(CnCloudMarket::getCloudMarketIndustryClassification, id)
                        .or()
                        .eq(CnCloudMarket::getCloudMarketGeneralClassification, id);
                    }));
            for (CnCloudMarket cloudMarket : list) {

                List<CnCloudMarketSku> skuList = cnCloudMarketSkuService.list(new LambdaQueryWrapper<CnCloudMarketSku>()
                        .eq(CnCloudMarketSku::getDeleteFlag, 0)
                        .eq(CnCloudMarketSku::getMarketId, cloudMarket.getMarketId()));

                Map<String, Object> map = new HashMap<>();
                map.put("productName", cloudMarket.getTitle());
                if(skuList.isEmpty()){
                    map.put("productConfig", "暂未");
                    map.put("amount", 0);
                    map.put("productCount", 1);
                } else {
                    CnCloudMarketSku cloudMarketSku = skuList.get(0);
                    String cloudMarketBuyingMethod = cloudMarketSku.getCloudMarketBuyingMethod();
                    if (cloudMarketBuyingMethod.equals("0")){
                        cloudMarketBuyingMethod = " * 1次";
                    } else if (cloudMarketBuyingMethod.equals("1")){
                        cloudMarketBuyingMethod = " * 1天";
                    } else if (cloudMarketBuyingMethod.equals("2")){
                        cloudMarketBuyingMethod = " * 1月";
                    } else if (cloudMarketBuyingMethod.equals("3")){
                        cloudMarketBuyingMethod = " * 1年";
                    } else {
                        cloudMarketBuyingMethod = "";
                    }
                    map.put("productConfig", cloudMarketSku.getFirstSkuName() + cloudMarketBuyingMethod);
                    map.put("amount", cloudMarketSku.getPrice());
                    map.put("productCount", 1);
                }
                result.add(map);
            }
        } else if ("3".equals(type)) {
            List<CnCommonCloud> list = cnCommonCloudService.list(new LambdaQueryWrapper<CnCommonCloud>()
                    .eq(CnCommonCloud::getDeleteFlag, 0)
                    .eq(CnCommonCloud::getServerTypeId, id));
            for (CnCommonCloud commonCloud : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("productName", commonCloud.getServerName());
                map.put("productConfig", "CPU:" + (StringUtils.isBlank(commonCloud.getCpu()) ? "无" : commonCloud.getCpu())
                        + " 内存:" + (StringUtils.isBlank(commonCloud.getMemory()) ? "无" : commonCloud.getMemory())
                        + " 硬盘大小:" + (StringUtils.isBlank(commonCloud.getHardDisk()) ? "无" : commonCloud.getHardDisk())
                        + " 防御:" + (StringUtils.isBlank(commonCloud.getDefense()) ? "无" : commonCloud.getDefense())
                        + " 带宽:" + (StringUtils.isBlank(commonCloud.getBandwidth()) ? "无" : commonCloud.getBandwidth())
                        + " 其他:" + (StringUtils.isBlank(commonCloud.getOther()) ? "无" : commonCloud.getOther()));
                map.put("amount", commonCloud.getPrice());
                map.put("productCount", 1);
                result.add(map);
            }
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("productName", "服务器");
            map.put("productConfig", "");
            map.put("amount", 0);
            map.put("productCount", 1);
            result.add(map);
        }

       return result;
    }

    @Override
    public Map<String, Object> statistics(CnVirtuallyUserBuyLog cnVirtuallyUserBuyLog) {
        QueryWrapper<CnVirtuallyUserBuyLog> queryWrapper = cnVirtuallyUserBuyLog.queryWrapper();
        List<CnVirtuallyUserBuyLog> cnVirtuallyUserBuyLogs = cnVirtuallyUserBuyLogMapper.selectCnVirtuallyUserBuyLogList(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("count", cnVirtuallyUserBuyLogs.size());
        map.put("userCount", cnVirtuallyUserBuyLogs.stream().map(CnVirtuallyUserBuyLog::getUserId).distinct().count());
        map.put("amount", cnVirtuallyUserBuyLogs.stream().map(CnVirtuallyUserBuyLog::getAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
        return map;
    }

    @Override
    public Map<String, String> virtuallyUserList() {
        List<CnVirtuallyUserHwAccount> list = virtuallyUserHwAccountService.lambdaQuery().eq(CnVirtuallyUserHwAccount::getDelFlag, 1).list();
        return list.stream().collect(Collectors.toMap(CnVirtuallyUserHwAccount::getUserId, CnVirtuallyUserHwAccount::getNickName));
    }
}
